package com.cn.mmd.controller;

import com.cn.mmd.model.*;
import com.cn.mmd.service.CourseService;
import com.cn.mmd.service.TeacherService;

import com.cn.mmd.tools.AliyunOssUtil;
import com.cn.mmd.tools.GetObjectProperty;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;



import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 教师登录
 * Created by Administrator on 2016/6/23.
 */

@Controller
@RequestMapping(value="/teacher")

public class TeacherController {
    @Autowired
    TeacherService teacherService;
    @Autowired
    CourseService courseService;
    @Autowired
    private TokenController tokenController;


    /**
     * 教师登录
     * @param request
     * @return
     */
//    @RequestMapping(value = "/teacherLogin")
//    public @ResponseBody Map<String,Object> TeacherLogin(HttpServletRequest request){
//        //前端传入账号和密码
//        String teacherId=request.getParameter("teacherId");
//        String teacherPassword=DigestUtils.md5Hex(request.getParameter("teacherPassword"));
//        System.out.println("前端传过来的加密后的密码："+teacherPassword);
//        TeacherData teacherData=teacherService.teacherLogin(teacherId, teacherPassword);
//        Map<String,Object> map = new HashMap<String,Object>();
//        Map<String,Object> map1 = new HashMap<String,Object>();
//        if(teacherData!=null){
//            if (teacherData.getTeacherpassword().equals(teacherPassword)){
//                System.out.print("登录成功");
//                map.put("code",200);
//                map.put("message","登录成功");
//                map.put("date","");
//                map1.putAll(map);
//            }else{
//                System.out.print("密码错误");
//
//                //  message="code:密码错误";
//                map.put("code",201);
//                map.put("message","密码错误");
//                map.put("date","");
//                map1.putAll(map);
//            }
//        }else{
//            System.out.print("账号不存在");
//
//            map.put("code",500);
//            map.put("message","账号不存在");
//            map.put("date","");
//            map1.putAll(map);
//        }
//
//        return map1;
//    }


    /**
     * 查询老师被阅读、评价、下载次数的统计次数
     * @param request
     * @return
     */
    @RequestMapping(value = "/selectStatistics")
    public synchronized @ResponseBody Map<String,Object> selectStatistics(HttpServletRequest request) {
        Map<String,Object> map = new HashMap<String,Object>();
        //前端传入教师工号
        String teacherid=request.getParameter("teacherId");

        TeacherStatistics teacherStatistics = teacherService.selectStatistics(teacherid);
        if (null==teacherStatistics){
            map.put("code",500);
            map.put("message","没有信息");
//            map.put("data","");

        }else{
            map.put("code",200);
            map.put("message","查询成功");
            map.put("data", teacherStatistics);
        }

        return map;
    }


    /**
     * 教师被阅读、评价、下载次数统计
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateStatistics")
    public synchronized @ResponseBody Map<String,Object> updateStatistics(HttpServletRequest request){
        Map<String,Object> map = new HashMap<String,Object>();
        Map<String,Object> map1 = new HashMap<String,Object>();

        // teacherId为当前教师的工号，data为要修改的统计项的名：beViewed、beComments或beDownloaded其中之一
//        String json=request.getParameter("statistics");
//        JSONObject jsonObject=JSONObject.fromObject(json);

        String teacherId=request.getParameter("teacherId");//前端传入教师工号
        String data=request.getParameter("type");//传入要修改的类型

        String operatorId=request.getParameter("operatorId");//调用此接口的人的id
        String operatorType=request.getParameter("operatorType");
        String token=request.getParameter("token");
        if (operatorType.equals("教师")){

            TeacherData teacherData;
            teacherData = (TeacherData) tokenController.token(operatorId, token);
            if (teacherData==null){
                map.put("code", 203);
                map.put("message", "您暂无权限做此操作");
//                map.put("data", "");
                return map;
            }

        }else if (operatorType.equals("学生")){
            StudentApp studentApp;
            studentApp = (StudentApp) tokenController.token1(operatorId, token);
            if (studentApp==null){
                map.put("code", 203);
                map.put("message", "您暂无权限做此操作");
//                map.put("data", "");
                return map;
            }
        }

        TeacherStatistics teacherStatistics = teacherService.selectStatistics(teacherId);

        if (teacherStatistics==null){
            TeacherStatistics teacherStatistics2=new TeacherStatistics();
            teacherStatistics2.setTeacherid(teacherId);
            if (data.equals("beViewed")){
                teacherStatistics2.setBeviewed(1);
                map1.put("beViewed",1);
            }else if (data.equals("beComments")){
                teacherStatistics2.setBecomments(1);
                map1.put("beComments",1);
            }else if (data.equals("beDownloaded")){
                teacherStatistics2.setBedownloaded(1);
                map1.put("beDownloaded",1);
            }else {
                map.put("code",202);
                map.put("message","传入信息错误！！！");
//                map.put("data","");
            }

            int a=teacherService.insertStatistics(teacherStatistics2);
            if (a>0){

                map.put("code",200);
                map.put("message","统计成功");
                map.put("data",map1);
            }else {
                map.put("code",201);
                map.put("message","统计失败");
//                map.put("data","");
            }

        }else {
            TeacherStatistics teacherStatistics1=new TeacherStatistics();
            teacherStatistics1.setTeacherid(teacherId);
            if (data.equals("beViewed")){
                int beViewed=teacherStatistics.getBeviewed();
                int beViewed1=beViewed+1;

                teacherStatistics1.setBeviewed(beViewed1);
                map1.put("beViewed",beViewed1);
                int b=teacherService.updateStatistics(teacherStatistics1);
                if (b>0){
                    //System.out.println("统计成功");
                    map.put("code",200);
                    map.put("message","统计成功");
                    map.put("data",map1);
                }else{
                    map.put("code",201);
                    map.put("message","统计失败");
//                    map.put("data","");
                }
            }else if (data.equals("beComments")){
                int beComments=teacherStatistics.getBecomments();
                int beComments1=beComments+1;

                teacherStatistics1.setBeviewed(beComments1);
                map1.put("beComments",beComments1);
                int b=teacherService.updateStatistics(teacherStatistics1);
                if (b>0){
                    //System.out.println("统计成功");
                    map.put("code",200);
                    map.put("message","统计成功");
                    map.put("data",map1);
                }else{
                    map.put("code",201);
                    map.put("message","统计失败");
//                    map.put("data","");
                }

            }else if (data.equals("beDownloaded")){
                int beDownloaded=teacherStatistics.getBedownloaded();
                int beDownloaded1=beDownloaded+1;

                teacherStatistics1.setBeviewed(beDownloaded1);
                map1.put("beDownloaded",beDownloaded1);
                int b=teacherService.updateStatistics(teacherStatistics1);
                if (b>0){
                    //System.out.println("统计成功");
                    map.put("code",200);
                    map.put("message","统计成功");
                    map.put("data",map1);
                }else{
                    map.put("code",201);
                    map.put("message","统计失败");
//                    map.put("data","");
                }
            }else{
                map.put("code",202);
                map.put("message","传入信息错误！！！");
//                map.put("data","");
            }

        }



        return map;
    }


    /**
     * 查看个人资料
     * @param request
     * @return
     */
    @RequestMapping(value = "/selectMydata")
    public synchronized @ResponseBody Map<String,Object> selectMydata(HttpServletRequest request){
        Map<String,Object> map = new HashMap<String,Object>();

        String teacherId=request.getParameter("teacherId");//前端传入老师工号
        String token = request.getParameter("token");

            TeacherData teacherData;
            teacherData = (TeacherData) tokenController.token(teacherId, token);

//       TeacherData teacherData=teacherService.selectByTeacherId(teacherId);

            if (null!=teacherData){

                Map<Object,Object> map2=new HashMap<Object,Object>();
                //  List l=new ArrayList();
                GetObjectProperty getObjectProperty=new GetObjectProperty();
                List list= getObjectProperty.getFiledsInfo(teacherData);
                for (int i=0;i<list.size();i++){
                    Map map1=(Map)list.get(i);
                    for(Object key:map1.keySet()){
                        if (key.equals("value")&&map1.get(key)==null){
                            map1.put(key,"");
                            list.add(map1);
                        }

                    }

                    map2.put(map1.get("name"),map1.get("value"));
                }
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String teacherAge = null;


                try {
                    if (teacherData.getMybirthd()==null||teacherData.getMybirthd().equals("")) {

                        map2.put("teacherAge","");
                    }else {
                        teacherAge = (date.getTime() - sdf.parse(teacherData.getMybirthd()).getTime()) / (1000 * 60 * 60 * 24) / 365 + "";
                        map2.put("teacherAge",teacherAge);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                TeacherStatistics teacherStatistics = teacherService.selectStatistics(teacherId);
                if (null==teacherStatistics){
                    map2.put("beviewed",0);
                    map2.put("becomments",0);
                    map2.put("bedownloaded",0);

                }else{
                    map2.put("beviewed",teacherStatistics.getBeviewed());
                    map2.put("becomments",teacherStatistics.getBecomments());
                    map2.put("bedownloaded",teacherStatistics.getBedownloaded());
                }

                map.put("code",200);
                map.put("message","查看成功");
                map.put("data",map2);
            }else {
                map.put("code",201);
                map.put("message","您暂无权限做此操作");
//                map.put("data","");
        }

        return map;
    }


    /**
     * 教师修改个人资料
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateMydata")
    public synchronized @ResponseBody Map<String,Object> updateMydata(HttpServletRequest request){
        Map<String,Object> map = new HashMap<String,Object>();

        String teacherId=request.getParameter("teacherId");//教师工号
        String teacherSex=request.getParameter("teacherSex");//教师性别
        String teacherphoneNumber=request.getParameter("teacherphoneNumber");//教师手机号
        //String teacherHeadPortrait=request.getParameter("teacherHeadPortrait");//头像url   要做文件上传！！！
        String mynickname=request.getParameter("mynickname");//昵称
        String mybirthd=request.getParameter("mybirthd");//生日
        String personalizedSignature=request.getParameter("personalizedSignature");//个性签名
        String token = request.getParameter("token");
        TeacherData teacherData2;
        teacherData2 = (TeacherData) tokenController.token(teacherId, token);
        if (teacherData2!=null){

            TeacherData teacherData=new TeacherData(teacherId,teacherSex,teacherphoneNumber,
                    mynickname,mybirthd,personalizedSignature);

            int i=teacherService.updateTeacher(teacherData);
            if (i>0){
//            TeacherData teacherData1=teacherService.selectByTeacherId(teacherId);

//            Map map2=new HashMap();
//            //  List l=new ArrayList();
//            GetObjectProperty getObjectProperty=new GetObjectProperty();
//            List list= getObjectProperty.getFiledsInfo(teacherData1);
//            for (int x=0;x<list.size();x++){
//                Map map1=(Map)list.get(x);
//                for(Object key:map1.keySet()){
//                    if (key.equals("value")&&map1.get(key)==null){
//                        map1.put(key,"");
//                        list.add(map1);
//                    }
//
//                }
//                map2.put(map1.get("name"),map1.get("value"));
//            }

                map.put("code",200);
                map.put("message","修改成功");
//                map.put("data","");
            }else{
                map.put("code",201);
                map.put("message","修改失败");
//                map.put("data","");
            }
        }else {
            map.put("code",202);
            map.put("message","您暂无权限做此操作");
//            map.put("data","");
        }

        return map;
    }

    /**
     * 修改密码
     * @param request
     * @return
     */
    @RequestMapping(value = "/updatePassword")
    public synchronized @ResponseBody Map<String,Object> updatePassword(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
//        Map<String, Object> objectMap = new HashMap<String, Object>();
        String teacherId = request.getParameter("teacherId");
        String password = request.getParameter("password");//老密码
        String password1 = request.getParameter("password1");//新密码
        String password2 = request.getParameter("password2");//验证新密码
        String token = request.getParameter("token");
        TeacherData teacherData;
        teacherData = (TeacherData) tokenController.token(teacherId, token);
        if (teacherData != null) {
            if (DigestUtils.md5Hex(password).equals(teacherData.getTeacherpassword())) {
                System.out.println(password+",");
                if (password1.equals(password2)) {
                    teacherData = new TeacherData();
                    teacherData.setTeacherid(teacherId);
                    teacherData.setTeacherpassword(DigestUtils.md5Hex(password1));
                    if (teacherService.updateTeacher(teacherData) > 0) {
                        map.put("code", 200);
                        map.put("message", "修改成功");
//                        map.put("data","");
                    } else {
                        map.put("code", 201);
                        map.put("message", "修改失败,请核对信息是否正确");
//                        map.put("data","");
                    }
                } else {

                    map.put("code", 202);
                    map.put("message", "两次密码不一致");
//                    map.put("data","");
                }
            } else {
                map.put("code", 203);
                map.put("message", "密码不正确");
//                map.put("data","");
            }
        }else {
            map.put("code", 204);
            map.put("message", "您暂无权限做此操作");
//            map.put("data","");

        }
        return map;
    }


    /**
     * 设置或修改头像
     * @param request
     * @return
     */
    @RequestMapping(value = "/updateTeacherHeadPortrait")
    public synchronized @ResponseBody Map<String,Object> updateTeacherHeadPortrait(HttpServletRequest request,@RequestParam(value = "file", required = false) MultipartFile file) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();

        String teacherId=request.getParameter("teacherId");
        String token = request.getParameter("token");

        //System.out.println("进入设置头像接口");
        TeacherData teacherData;
        teacherData = (TeacherData) tokenController.token(teacherId, token);
//        TeacherData teacherData=teacherService.selectByTeacherId(teacherId);

        if (teacherData != null) {
            String path = request.getSession().getServletContext().getRealPath("/") + "upload";
            String studentHeadPortraitUrl;
            File targetFile;
            if (file == null) {
                studentHeadPortraitUrl = "";
            } else {
                String key = teacherId + "-HeadPortrait-" + file.getOriginalFilename();
                targetFile = new File(path, key);
                if (!targetFile.exists()) {
                    try {
                        file.transferTo(targetFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    targetFile.delete();
                    try {
                        file.transferTo(targetFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                studentHeadPortraitUrl = AliyunOssUtil.save(key, targetFile.getPath());
                targetFile.delete();
            }
            TeacherData teacherData1=new TeacherData();
            teacherData1.setTeacherid(teacherId);
            teacherData1.setTeacherheadportrait(studentHeadPortraitUrl);
            int b=teacherService.updateTeacher(teacherData1);
            if (b>0){
                map.put("code",200);
                map.put("message","设置头像成功");
//                map.put("data","");
            }else {
                map.put("code",400);
                map.put("message","设置头像失败");
//                map.put("data","");
            }

        }else {
            map.put("code",201);
            map.put("message","您暂无权限做此操作");
//            map.put("data","");
        }
        return map;
    }



    /**
     * 通过教师id查询这个教师所教的所有班级
     * @param request
     * @return
     * @throws com.alibaba.fastjson.JSONException
     */
    @RequestMapping(value = "selectClassByTeacher")
    public synchronized @ResponseBody Map<String,Object> selectClassByTeacher(HttpServletRequest request)throws Exception {

        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> map1 = new HashMap<String, Object>();

        String teacherId=request.getParameter("teacherId");//教师id
        String token=request.getParameter("token");

        TeacherData teacherData;
        teacherData = (TeacherData) tokenController.token(teacherId, token);
        if (teacherData==null){
            map.put("code", 201);
            map.put("message", "您暂无权限做此操作");
//            map.put("data", "");
            return map;
        }


        List<Course> courseList=courseService.selectClassByTeacher(teacherId);

        List list=new ArrayList();
        if (courseList.size()>0){
            for (int i=0;i<courseList.size();i++){

                String Classes=courseList.get(i).getCourseclasss();
                String[] c=Classes.split(",");
                for (int j=0;j<c.length;j++){
                    //System.out.print("   所有班级：" + c[j]);
                    map1.put(c[j], c[j]);
                }
            }
            //System.out.println();
            for (String m:map1.keySet()){
                //System.out.print("   m："+m);
                list.add(m);
            }

            map.put("code",200);
            map.put("message","查询成功");
            map.put("date",list);
        }else {
            map.put("code",400);
            map.put("message","查询失败");
            map.put("date","");
        }

        return map;
    }





//    /**
//     * 查看周统计结果
//     * @param request
//     * @return
//     */
//    @RequestMapping(value = "/selectWeekStatistics")
//    public synchronized @ResponseBody Map<String, Object> selectWeekStatistics(HttpServletRequest request) {
//        Map<String, Object> map = new HashMap<String, Object>();
//
//        List<WeekStatistics> weekStatisticses=teacherService.selectNewStatistics();
//        if (weekStatisticses.size()>0){
//            map.put("code",200);
//            map.put("message","查询成功");
//            map.put("data",weekStatisticses);
//        }else {
//            map.put("code",201);
//            map.put("message","查询失败");
//            map.put("data","");
//        }
//        return map;
//
//    }
}
